<?php

namespace app\admin\controller\retail;

use app\common\controller\Backend;
use app\common\library\Auth;
use app\common\model\RetailUser;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'uid,user.username,user.nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('RetailUser');
    }

    /**
     * 查看
     */
    public function index()
    {

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();

            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
//            $list = $this->model
//                ->alias('retail_user')
//                ->field("retail_user.*,user.username,user.avatar,user.nickname,user.gender")
//                ->join('user user','user.id = retail_user.uid')
//                ->where($where)
//                ->order($sort, $order)
//                ->paginate($limit);

            $list = $this->model
                ->with('user')
                ->where($where)
                ->paginate($limit);

            foreach ($list as $k => $v) {
                $v->user->avatar = $v->user->avatar ? cdnurl($v->user->avatar, true) : letter_avatar($v->user->nickname);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        return parent::add();
    }


    // /**
    //  * 编辑
    //  */
    // public function edit($ids = null)
    // {
    //     if ($this->request->isPost()) {
    //         $this->token();
    //     }
    //     $row = $this->model->get(['uid'=>$ids]);
    //     // $this->modelValidate = true;
    //     if (!$row) {
    //         $this->error(__('No Results were found'));
    //     }
    //     $this->view->assign('groupList', build_select('row[id]', 
    //     [1=>'粉丝',2=>'玩客',3=>'玩主',4=>'玩家'], $row['id'], ['class' => 'form-control selectpicker']));
    //     return parent::edit(['uid' =>$ids]);
    // }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {

            $params = $this->request->post("row/a");
            //$red = $this->model->update($params);
            $ret = $this->changeParent($params);
            if($ret === 1){
                $this->token();
                $this->success();
            }else{
                $this->error($ret);
            }

        }else{
            $row = db('retail_user')->where('uid',$ids)->find();
            $this->view->assign('groupList', build_select('row[level]',
                [1=>'粉丝',2=>'玩客',3=>'玩主',4=>'玩家'], $row['level'], ['class' => 'form-control selectpicker']));
            $this->view->assign("row", $row);
            return $this->view->fetch();
        }

    }

    /**
     * 删除
     */
//    public function del($ids = "")
//    {
//        if (!$this->request->isPost()) {
//            $this->error(__("Invalid parameters"));
//        }
//        $ids = $ids ? $ids : $this->request->post("ids");
//        $row = $this->model->get($ids);
//        $this->modelValidate = true;
//        if (!$row) {
//            $this->error(__('No Results were found'));
//        }
//        Auth::instance()->delete($row['id']);
//        $this->success();
//    }

    /**
     * 改变上级
     */
    public function changeParent($params)
    {
        $child_user_id = $params['uid'];//需要修改的下级会员ID
        $new_parent_id = $params['pid'];//更换之后的上级会员ID

        //会员是否存在上级
        $retailUser = model('retail_user')->getUserInfo($child_user_id);
        if(empty($retailUser) ){
            return '非会员';
        }elseif($retailUser['level'] == RetailUser::LEVEL_WANZHU){
            return "玩主不能更换上级";
        }elseif($retailUser['level'] == RetailUser::LEVEL_WANJIA){
            return "玩家不能更换上级";
        }elseif($retailUser['wanzhu_total'] > 0){
            return "此会员已经有育成玩主,不能更换";
        }elseif($retailUser['wanjia_total'] > 0){
            return "此会员已经有育成玩家,不能更换";
        }elseif($retailUser['level'] == RetailUser::LEVEL_FENS && $retailUser['wanke_total'] > 0 ){
            return "此会员是粉丝已经有育成玩客了,不能更换";
        }elseif($child_user_id == $new_parent_id){
            return "自己不能是自己的上级";
        }elseif($retailUser['pid'] == $new_parent_id){
            return "没有改变用户上级";
        }

        $newParentUser = model('retail_user')->getUserInfo($new_parent_id);
        if(empty($newParentUser)){
            return "新上级非会员,无效";
        }

        /***************重新计算原来上级的团队人数,减掉相应的数量,循环所有旧上级 BEGIN**************/
        $old_parent_ids = [];
        $old_pid = $retailUser['pid'];
        $child = $retailUser;
        while( !empty($child)){
            //旧上级会员
            $parent = db('retail_user')->where(['uid'=>$child['pid']])->find();
            if(empty($parent) || $parent['uid'] == $child['uid']){
                break;
            }
            $old_parent_ids[] = $parent['uid'];
            //继续获取下一个上级信息
            $child  = $parent;
        }

        //新的上级ID集合
        $new_parent_ids = [$new_parent_id];
        $child = $newParentUser;
        while( !empty($child)){
            //新上级会员
            $parent = db('retail_user')->where(['uid'=>$child['pid']])->find();
            if(empty($parent) || $parent['uid'] == $child['uid']){
                break;
            }
            $new_parent_ids[] = $parent['uid'];
            //继续获取下一个上级信息
            $child  = $parent;
        }

        //判断A的上级是否有B的下级
        $retailUserModel = new RetailUser();
        $all_children_ids = $retailUserModel->fensPersonList($retailUser, 0, 1);
        if(!empty(array_intersect($new_parent_ids,$all_children_ids))){
            $msg = "新上级会员的上级ID:".implode(',',$new_parent_ids)."--当前用户的下级ID:".implode(',',$all_children_ids);
            return "新上级的上级有当前用户的下级,更改后会形成死循环.详细原因:".$msg;
        }

        $parent_ids = array_unique(array_merge(array_diff($old_parent_ids,$new_parent_ids),array_diff($new_parent_ids,$old_parent_ids),[$new_parent_id,$retailUser['pid']]));



        //更新变更会员的上级ID
        db('retail_user')->where(['uid'=>$retailUser['uid']])->update(['pid'=>$newParentUser['uid']]);
        //重新计算团队人数
        RetailUser::repaire($parent_ids);
        \think\Log::log("成功修改用户{$retailUser['uid']}的上级会员,原来上级ID:{$old_pid},新的上级ID:{$new_parent_id}");
        return 1;

    }

}
